#!/usr/bin/env python

import os
import wx
import app
import dialog
import urllib2
import component

from poster.encode import multipart_encode
from poster.encode import MultipartParam
from poster.streaminghttp import register_openers

class Main(component.Presenter):
    '''Main class
    
    @author Julot <andy.julot@gmail.com>
    @since Saturday, January 14, 2012. 09:07 AM'''
    
    _folder = ''
    _image = ''
    
    def __init__(self, view, interactor):
        super(Main, self).__init__(view, interactor)
        self.readVerSashPos()
        self.readHorSashPos()
        self.readFolder()
        self.populateFiles(self._folder)
        
    def onClose(self):
        self.writeVerSashPos()
        self.writeHorSashPos()
        self.writeFolder()
        super(Main, self).onClose()
    
    def close(self):
        self.view.Close()
    
    def readVerSashPos(self):
        pos = app.Config().ReadInt('%s/VerSash' % self.view.Name, -1)
        if pos != -1: self.view.vSplitter.SashPosition = pos
    
    def readHorSashPos(self):
        pos = app.Config().ReadInt('%s/HorSash' % self.view.Name, -1)
        if pos != -1: self.view.hSplitter.SashPosition = pos
    
    def readFolder(self):
        self._folder = app.Config().Read('%s/Folder' % self.view.Name, '')
    
    def writeVerSashPos(self):
        key = '%s/VerSash' % self.view.Name
        app.Config().WriteInt(key, self.view.vSplitter.SashPosition)
    
    def writeHorSashPos(self):
        key = '%s/HorSash' % self.view.Name
        app.Config().WriteInt(key, self.view.hSplitter.SashPosition)
    
    def writeFolder(self):
        key = '%s/Folder' % self.view.Name
        app.Config().Write(key, self._folder)
    
    _about = None
    
    def showAbout(self):
        if not self._about: self._about = dialog.About(self.view)
        self._about.Center()
        self._about.Show()

    def browse(self):
        folder = self.view.dirDialog(defaultPath=self._folder,
                                     style=wx.DD_DIR_MUST_EXIST)
        if folder: self.populateFiles(folder)
    
    def populateFiles(self, folder):
        if not os.path.lexists(folder): return
        
        self._folder = folder
        exts = ('png', 'jpg', 'jpeg', 'gif')
        filenames = os.listdir(folder)
        files = []
        for filename in filenames:
            name, ext = os.path.splitext(filename)
            ext = ext.lower()[1:]
            if ext in exts:
                files.append(filename)
        self.view.files.values = files
    
    def update(self):
        if not self._image:
            message = 'Please select image.'
            self.view.messageDialog(message, 'Error')
            return
        
        code = self.view.form.code.Value
        if not code:
            message = 'No cannot be blank'
            self.view.messageDialog(message, 'Error')
            return
        
        synopsis = self.view.form.synopsis.Value
        if not synopsis:
            message = 'Synopsis cannot be blank'
            self.view.messageDialog(message, 'Error')
            return
        
        self.view.busyCursor()
        self.view.form.disable()
        path = os.path.join(self._folder, self._image)
        if not self.upload(open(path, 'rb'), code, synopsis):
            s = 'Update failed.\n' + \
              'Please try again later or contact your administrator.'
            self.view.messageDialog(s, 'Update')
        else:
            self.view.form.code.Value = ''
            self.view.form.synopsis.Value = ''
            os.unlink(path)
            self.populateFiles(self._folder)
            self.view.image.clear()
        self.view.form.enable()
        self.view.idle()
        
    def upload(self, fileObject, code, synopsis):
        #url = 'http://localhost/Aya/Miyabi/api/document'
        url = 'http://apl.pojokdomain.com/miyabi/api/document'
        
        register_openers()
        
        params = {'Document[file]': fileObject, 'code': code,
                  'synopsis': synopsis}
        datagen, headers = multipart_encode(params)
        request = urllib2.Request(url, datagen, headers)
        request.add_header('X_REST_USERNAME', 'rest-user@miyabi')
        request.add_header('X_REST_PASSWORD', 'MiyabiRestUser')
        
        try:
            res = urllib2.urlopen(request).read()
            return True
        except:
            return False
        
    def show(self, filename):
        self._image = filename
        path = os.path.join(self._folder, filename)
        try:
            image = wx.Image(path, wx.BITMAP_TYPE_ANY)
        except:
            self.view.messageDialog('Invalid image', 'Error', wx.OK)
        else:
            self._show(image)
    
    def _show(self, image):
        if not image: return
        
        self.view.busyCursor()
        
        canvas = self.view.image
        canvas.maxWidth = image.Width
        canvas.maxHeight = image.Height
        canvas.SetVirtualSize((canvas.maxWidth, canvas.maxHeight))
        
        canvas.pdc.BeginDrawing()
        canvas.pdc.Clear()
        canvas.pdc.DrawBitmap(image.ConvertToBitmap(), 0, 0, False)
        canvas.pdc.EndDrawing()
        canvas.Refresh()
        
        self.view.idle()